package com.sailboard.iot.opm.service.equipment.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sailboard.iot.opm.common.JsonResult;
import com.sailboard.iot.opm.common.ResultCode;
import com.sailboard.iot.opm.common.SystemCodeConstants;
import com.sailboard.iot.opm.dao.entity.*;
import com.sailboard.iot.opm.dao.mapper.*;
import com.sailboard.iot.opm.service.equipment.EquipmentService;
import com.sailboard.iot.opm.service.qrcode.OssUtil;
import com.sailboard.iot.opm.service.qrcode.QrCodeUtil;
import com.sailboard.iot.opm.utils.BeanMapUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * java类简单作用描述
 *
 * @ProjectName: iot-opm
 * @Package: com.sailboard.iot.opm.service.equipment.impl
 * @ClassName: ${TYPE_NAME}
 * @Description: java类作用描述
 * @Author: 候杰
 * @CreateDate: 2017/12/25 20:45
 * @UpdateUser: Neil.Zhou
 * @UpdateDate: 2017/12/25 20:45
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * Copyright: Copyright (c) 2017
 */
@Component
public class EquipmentServiceImpl implements EquipmentService {

    @Resource
    TerminalMapper terminalMapper;
    @Resource
    ConsoleMapper consoleMapper;
    @Resource
    ChargingStationMapper chargingStationMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserRoleMapper userRoleMapper;
    @Resource
    CompanyMapper companyMapper;

    @Override
    public PageInfo getTerminalList(int pageNum, int pageSize, Terminal terminal){
        PageHelper.startPage(pageNum, pageSize);
        List<Terminal> list = terminalMapper.getTerminalList(BeanMapUtils.toMap(terminal));
        return new PageInfo(list);
    }
    @Override
    public boolean addTerminal(Terminal terminal){
        return terminalMapper.insertSelective(terminal)==1;
    }
    @Override
    public boolean deleteTerminal(Long terminalId){
        return terminalMapper.deleteByPrimaryKey(terminalId)==1;
    }

    @Override
    public boolean batchDelTerminal(String ids){
        String[] arr = ids.split(",");
        List<Long> delList = new ArrayList<>();
        List<String> cannotDelList = new ArrayList<>();
        for(String id : arr) {
            long roleId = Long.valueOf(id);
            delList.add(Long.valueOf(id));
        }
        int row = terminalMapper.batchDelete(delList);
        return row > 0;
    }

    @Override
    public boolean updateTerminal(Terminal terminal){
        return terminalMapper.updateByPrimaryKeySelective(terminal)==1;
    }
    @Override
    public boolean updateTerminalStatus(Long id,Integer status){
        return terminalMapper.updateTerminalStatus(id, status) == 1;
    }

    @Override
    public PageInfo getConsoleList(int pageNum, int pageSize, Console console){
        PageHelper.startPage(pageNum, pageSize);
        List<Console> list = consoleMapper.getConsoleList(BeanMapUtils.toMap(console));
        return new PageInfo(list);
    }
    @Override
    public boolean addConsole(Console console){
        return consoleMapper.insertSelective(console)==1;
    }
    @Override
    public boolean deleteConsole(Long consoleId){
        return consoleMapper.deleteByPrimaryKey(consoleId)==1;
    }
    @Override
    public boolean updateConsole(Console console){
        return consoleMapper.updateByPrimaryKeySelective(console)==1;
    }
    @Override
    public boolean updateConsoleStatus(Long id,Integer status){
        return consoleMapper.updateConsoleStatus(id, status) == 1;
    }

    @Override
    public boolean batchDelConsole(String ids){
        String[] arr = ids.split(",");
        List<Long> delList = new ArrayList<>();
        List<String> cannotDelList = new ArrayList<>();
        for(String id : arr) {
            long roleId = Long.valueOf(id);
            delList.add(Long.valueOf(id));
        }
        int row = consoleMapper.batchDelete(delList);
        return row > 0;
    }




    @Override
    public PageInfo getChargingStationList(int pageNum, int pageSize, ChargingStation chargingStation){
        PageHelper.startPage(pageNum, pageSize);
        List<ChargingStation> list = chargingStationMapper.getChargingStationList(BeanMapUtils.toMap(chargingStation));
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        String username = currentUser.getPrincipals().toString();
        User user = userMapper.getByUsername(username);
        UserRole ur = userRoleMapper.selectByUserId(user.getId());
        if(!list.isEmpty()){
            list.get(0).setCurrentUser(ur.getRoleId());
        }
        return new PageInfo(list);
    }
    @Override
    public boolean addChargingStation(ChargingStation chargingStation){
        return chargingStationMapper.insertSelective(chargingStation)==1;
    }
    @Override
    public boolean deleteChargingStation(Long chargingStationId){
        return chargingStationMapper.deleteByPrimaryKey(chargingStationId)==1;
    }
    @Override
    public boolean updateChargingStation(ChargingStation chargingStation){
        return chargingStationMapper.updateByPrimaryKeySelective(chargingStation)==1;
    }
    @Override
    public boolean updateChargingStationStatus(Long id,Integer status){
        return chargingStationMapper.updateStationStatus(id, status) == 1;
    }

    @Override
    public boolean batchDelChargingStation(String ids){
        String[] arr = ids.split(",");
        List<Long> delList = new ArrayList<>();
        List<String> cannotDelList = new ArrayList<>();
        for(String id : arr) {
            long roleId = Long.valueOf(id);
            delList.add(Long.valueOf(id));
        }
        int row = chargingStationMapper.batchDelete(delList);
        return row > 0;
    }

    @Override
    public JsonResult bindingTerminal(Long consoleId, String serialNumber) {
        List<Terminal> terminalList = terminalMapper.selectBySerialNumber(serialNumber);
        if (terminalList.size() < 1) {
            return new JsonResult(ResultCode.ERROR_CODE_701, ResultCode.ERROR_CODE_701_MSG_1);
        } else if (terminalList.size() == 1){
            if (terminalList.get(0).getConsoleId() == null) {
                if (terminalList.get(0).getStatus() != 1) {
                    return new JsonResult(ResultCode.ERROR_CODE_703, ResultCode.ERROR_CODE_703_MSG_1);
                }
                Console console = consoleMapper.selectByPrimaryKey(consoleId);
                if (console.getTerminalNumber() != null) {
                    terminalMapper.updateBySerialNumber(consoleId, serialNumber);
                    int tn = console.getTerminalNumber();
                    tn += 1;
                    consoleMapper.updateByTerminalNumber(consoleId, tn);
                    return JsonResult.success();
                } else {
                    terminalMapper.updateBySerialNumber(consoleId, serialNumber);
                    int tn = 1;
                    consoleMapper.updateByTerminalNumber(consoleId, tn);
                    return JsonResult.success();
                }
            } else {
                return new JsonResult(ResultCode.ERROR_CODE_701, ResultCode.ERROR_CODE_701_MSG_2);
            }
        }else {
            return new JsonResult(ResultCode.ERROR_CODE_702, ResultCode.ERROR_CODE_702_MSG);
        }
    }

    @Override
    public JsonResult bindingAgent(Long stationId, String agentName) {
        ChargingStation chargingStation = chargingStationMapper.selectByPrimaryKey(stationId);
        Company company = companyMapper.selectByAgentName(agentName);
        if ( company == null) {
            return new JsonResult(ResultCode.ERROR_CODE_704, ResultCode.ERROR_CODE_704_MSG);
        } else {
            if (chargingStation.getManagerName() == null) {
               chargingStationMapper.updateStationAgent(stationId, company.getId(), company.getName());
               return JsonResult.success();
            } else {
                return new JsonResult(ResultCode.ERROR_CODE_705, ResultCode.ERROR_CODE_705_MSG);
            }
        }
    }

    @Override
    public JsonResult bindingConsole(Long stationId, String serialNumber) {
        List<Console> consoleList = consoleMapper.selectBySerialNumber(serialNumber);
        if (consoleList.size() < 1) {
            return new JsonResult(ResultCode.ERROR_CODE_701, ResultCode.ERROR_CODE_701_MSG_1);
        } else if (consoleList.size() == 1) {
            if (consoleList.get(0).getStationId() == null) {
                if (consoleList.get(0).getStatus() != 1) {
                    return new JsonResult(ResultCode.ERROR_CODE_703, ResultCode.ERROR_CODE_703_MSG_2);
                }
                consoleMapper.updateBySerialNumber(stationId, serialNumber);
                return JsonResult.success();
            } else {
                return new JsonResult(ResultCode.ERROR_CODE_701, ResultCode.ERROR_CODE_701_MSG_2);
            }
        } else {
            return new JsonResult(ResultCode.ERROR_CODE_702, ResultCode.ERROR_CODE_702_MSG);
        }
    }

    //代理商获取设备情况列表（中控+partner+agent）
    @Override
    public PageInfo getAgentEquipmentSituationList(int pageNum, int pageSize, EquipmentSituation equipmentSituation){
        PageHelper.startPage(pageNum, pageSize);
        List<EquipmentSituation> list = consoleMapper.getAgentEquipmentSituationList(BeanMapUtils.toMap(equipmentSituation));
        return new PageInfo(list);
    }

    //平台公司商获取设备情况列表（中控+partner+agent）
    @Override
    public PageInfo getCompanyEquipmentSituationList(int pageNum, int pageSize, EquipmentSituation equipmentSituation){
        PageHelper.startPage(pageNum, pageSize);
        List<EquipmentSituation> list = consoleMapper.getCompanyEquipmentSituationList(BeanMapUtils.toMap(equipmentSituation));
        return new PageInfo(list);
    }
  //合作伙伴获取设备情况列表（中控+partner+agent）
  @Override
  public PageInfo getPartnerEquipmentSituationList(int pageNum, int pageSize, EquipmentSituation equipmentSituation) {
      PageHelper.startPage(pageNum, pageSize);
      List<EquipmentSituation> list = consoleMapper.getPartnerEquipmentSituationList(BeanMapUtils.toMap(equipmentSituation));
      return new PageInfo(list);
  }

    //代理商查看中控
    @Override
    public PageInfo getConsoleListByPartnerId(int pageNum, int pageSize, Console console){
        PageHelper.startPage(pageNum, pageSize);
        List<Console> list = consoleMapper.getConsoleListByPartnerId(BeanMapUtils.toMap(console));
        return new PageInfo(list);
    }

    //查看平台公司管理代理商绑定设备和未绑定设备列表
    @Override
    public PageInfo getCompanyAgentConsoleList(int pageNum, int pageSize, Console console) {
        PageHelper.startPage(pageNum,pageSize);
        List<Console> list = consoleMapper.getCompanyAgentConsole(BeanMapUtils.toMap(console));
        return new PageInfo(list);
    }



    @Override
    public boolean unBindConsole(Console console) {
        return consoleMapper.unBindConsole(console.getId())==1;
    }

    //解除电站和中控的绑定
    @Override
    public boolean unBindStationConsole(Console console) {
        return consoleMapper.unBindStationConsole(console) == 1;
    }


    //代理商查看终端
    @Override
    public PageInfo getTerminalListByPartnerId(int pageNum, int pageSize, Terminal terminal){
        PageHelper.startPage(pageNum, pageSize);
        List<Terminal> list = terminalMapper.getTerminalListByPartnerId(BeanMapUtils.toMap(terminal));
        return new PageInfo(list);
    }

    @Override
    public JsonResult batchAddQrCode(String ids) {

        String[] arr = ids.split(",");
        List<Long> list = new ArrayList<>();
        for(String id : arr) {
            Long cid = Long.valueOf(id);
            Console console = consoleMapper.selectByPrimaryKey(cid);
            try {
                //QRcode 二维码生成测试
                String content = SystemCodeConstants.ORBASE_URL+console.getTerminalNumber();
//                String imgPath = System.getProperty("user.dir")+"/iot-opm-main/deploy/static/images/qrcodes/qrcode"+cid+".jpg";
                String imgPath =SystemCodeConstants.OSS_ORBASE_URL_BD+ File.separator;
//                String imgPath =SystemCodeConstants.OSS_ORBASE_URL_BD+ "/";
                if (console.getQrCode()==null||console.getQrCode().equals("")){
                    QrCodeUtil.QRCodeCreate(content, imgPath, 15, null,console.getBusinessCode()+".png");
                    console.setQrCode(imgPath);
                    console.setQrCodeUrl(content);
                    consoleMapper.updateByPrimaryKey(console);
                }
            } catch (Exception e) {
                return JsonResult.error();
            }
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult batchAddTerminalQrCode(String ids) {

        String[] arr = ids.split(",");
        List<Long> list = new ArrayList<>();
        for(String id : arr) {
            Long cid = Long.valueOf(id);
            Terminal terminal = terminalMapper.selectByPrimaryKey(cid);
            try {
                String content = SystemCodeConstants.ORBASE_URL+terminal.getMachineCode();
                System.getProperty("user.dir");
                //String imgPath = System.getProperty("user.dir")+"/iot-opm-main/deploy/static/images/qrcodes/qrCode"+cid+".jpg";
//                String imgPath =SystemCodeConstants.OSS_ORBASE_URL_BD+ File.separator+terminal.getMachineCode()+".png";
                String imgPath =SystemCodeConstants.OSS_ORBASE_URL_BD+ File.separator;
//                String imgPath =SystemCodeConstants.OSS_ORBASE_URL_BD+ "/";
                if (terminal.getQrCode()==null||terminal.getQrCode().equals("")){
                    QrCodeUtil.QRCodeCreate(content, imgPath, 15, null,terminal.getBusinessCode()+".png");
                    terminal.setQrCode(imgPath);
                    terminal.setQrCodeUrl(content);
                    terminalMapper.updateByPrimaryKey(terminal);
                    //下面删除OSS二维码
//                    String name = SystemCodeConstants.OSS_ORBASE_URL+"/"+terminal.getMachineCode()+".jpg";
//                    if(OssUtil.isFileExist(name)){
//                        OssUtil.deleteFile(name);
//                    }
                }
            } catch (Exception e) {
                return JsonResult.error();
            }
        }
        return JsonResult.success();
    }
    @Override
    public PageInfo getConsoleForStationList(int pageNum,int pageSize,Console console){
        PageHelper.startPage(pageNum, pageSize);
        List<Console> list = consoleMapper.getConsoleForStationList(BeanMapUtils.toMap(console));
        return new PageInfo(list);
    }

    @Override
    public ChargingStation getChargingStationById(Long stationId) {
        return chargingStationMapper.selectByPrimaryKey(stationId);
    }

    @Override
    public Console getConsoleByConsole(Console console){return consoleMapper.getConsoleByConsole(console);}

    @Override
    public boolean batchDisableConsole(String ids) {
        List<Long> list = new ArrayList<>();
        String[] arr = ids.split(",");
        for(String id : arr) {
            long consoleId = Long.valueOf(id);
            if(consoleId >= 0) {
                list.add(Long.valueOf(id));
            }
        }
        return consoleMapper.batchDisableConsole(list) > 0;
    }

    @Override
    public boolean batchEnableConsole(String ids) {
        List<Long> list = new ArrayList<>();
        String[] arr = ids.split(",");
        for(String id : arr) {
            long consoleId = Long.valueOf(id);
            if(consoleId >= 0) {
                list.add(Long.valueOf(id));
            }
        }
        return consoleMapper.batchEnableConsole(list) > 0;
    }

    @Override
    public Console getConsoleByMachineCode(Console console){return consoleMapper.getConsoleByMachineCode(console);}

    @Override
    public Console getConsoleByBusinessCode(Console console){return consoleMapper.getConsoleByBusinessCode(console);}

    @Override
    public Terminal getTerminalByMachineCode(Terminal terminal){return terminalMapper.getTerminalByMachineCode(terminal);}

    @Override
    public Terminal getTerminalByBusinessCode(Terminal terminal){return terminalMapper.getTerminalByBusinessCode(terminal);}

    //批量禁用、启用终端
    @Override
    public boolean batchDisableTerminal(String ids) {
        List<Long> list = new ArrayList<>();
        String[] arr = ids.split(",");
        for(String id : arr) {
            long terminalId = Long.valueOf(id);
            if(terminalId >= 0) {
                list.add(Long.valueOf(id));
            }
        }
        return terminalMapper.batchDisableTerminal(list) > 0;
    }

    @Override
    public boolean batchEnableTerminal(String ids) {
        List<Long> list = new ArrayList<>();
        String[] arr = ids.split(",");
        for(String id : arr) {
            long terminalId = Long.valueOf(id);
            if(terminalId >= 0) {
                list.add(Long.valueOf(id));
            }
        }
        return terminalMapper.batchEnableTerminal(list) > 0;
    }
    public Console getConsoleById(Long id){return  consoleMapper.getConsoleById(id);}
}
